#ifndef __BSP_I2C_H__
#define __BSP_I2C_H__


#include "imx6u.h"

/* 定义相关宏 */
#define I2C_STATUS_OK					(0)
#define I2C_STATUS_BUSY					(1)
#define I2C_STATUS_IDLE					(2)
#define I2C_STATUS_NAK					(3)
#define I2C_STATUS_ARBITRATIONLOST		(4)		/* 仲裁丢失 */
#define I2C_STATUS_TIMEOUT				(5)
#define I2C_STATUS_ADDRNAK				(6)


#define _I2C_I2SR_IBB_SHIFT							(5)
#define _I2C_I2SR_IBB_MASK							(1 << _I2C_I2SR_IBB_SHIFT)

#define _I2C_I2CR_RSTA_SHIFT						(2)
#define _I2C_I2CR_RSTA_MASK							(1 << _I2C_I2CR_RSTA_SHIFT)
#define _I2C_I2CR_TXAK_SHIFT						(3)
#define _I2C_I2CR_TXAK_MASK							(1 << _I2C_I2CR_TXAK_SHIFT)
#define _I2C_I2CR_MTX_SHIFT							(4)
#define _I2C_I2CR_MTX_MASK							(1 << _I2C_I2CR_MTX_SHIFT)
#define _I2C_I2CR_MSTA_SHIFT						(5)
#define _I2C_I2CR_MSTA_MASK							(1 << _I2C_I2CR_MSTA_SHIFT)

#define _I2C_I2CR_TXAK_ACK_SIGNAL					(0x0)
#define _I2C_I2CR_TXAK_NAK_SIGNAL					(0x1)

#define _I2C_I2DR_DATA_SHIFT						(0)
#define _I2C_I2DR_DATA_MASK							(0xFF << _I2C_I2DR_DATA_SHIFT)
#define _I2C_I2DR_DATA_SLAVE_ADDR_SHIFT				(1)
#define _I2C_I2DR_DATA_SLAVE_ADDR_MASK				(0x7F << _I2C_I2DR_DATA_SLAVE_ADDR_SHIFT)
#define _I2C_I2DR_DATA_DIR_SHIFT					(0)
#define _I2C_I2DR_DATA_DIR_MASK						(0x1 << _I2C_I2DR_DATA_DIR_SHIFT)
#define _I2C_I2DR_DATA_DIR_READ						(1)
#define _I2C_I2DR_DATA_DIR_WRITE					(0)


/* 传输方向结构体 */
enum i2c_direction {
	kI2C_Write = 0x00,		/* 主机向从机发送数据 */
	kI2C_Read  = 0x01,		/* 从机向主机读取数据 */
};


/*
 * 主机传输结构体
 */
struct i2c_transfer
{
    unsigned char slaveAddress;      	/* 7位从机地址 			*/
    enum i2c_direction direction; 		/* 传输方向 			*/
    unsigned int subaddress;       		/* 寄存器地址			*/
    unsigned char subaddressSize;    	/* 寄存器地址长度 			*/
    unsigned char *volatile data;    	/* 数据缓冲区 			*/
    volatile unsigned int dataSize;  	/* 数据缓冲区长度 			*/
};



void i2c_init(I2C_Type *base);
unsigned char i2c_master_start(I2C_Type *base, unsigned char address, enum i2c_direction direction);
unsigned char i2c_master_stop(I2C_Type *base);
unsigned char i2c_check_and_clear_error(I2C_Type *base, unsigned int state);
unsigned char i2c_master_repeated_start(I2C_Type *base, unsigned char address, 
								enum i2c_direction direction);
void i2c_master_write(I2C_Type *base, const unsigned char *buf, unsigned int size);
void i2c_master_read(I2C_Type *base, unsigned char *buf, unsigned int size);
unsigned char i2c_master_transfer(I2C_Type *base, struct i2c_transfer *xfer);
#endif